package com.zhongyu.AreaJson.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: zhongyu
 * @Date: 2018/8/24 16:14
 * @Description:
 */
public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    /**
     * 读文件
     *
     * @param filePath
     * @return
     */
    public static String read(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.error(MessageFormat.format("[FileUtil]: File:{0} not exists!", filePath));
        }
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Throwable e) {
            logger.error(MessageFormat.format("[FileUtil]: File:{0} read error!", filePath));
        } finally {
            if (reader != null) {
                try {
                    //关闭文件
                    reader.close();
                } catch (Throwable e) {
                    logger.error(MessageFormat.format("[FileUtil]: File:{0} close error!", filePath));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取路径下的所有文件/文件夹
     * @param directoryPath 需要遍历的文件夹路径
     * @param isAddDirectory 是否将子文件夹的路径也添加到list集合中
     * @return
     */
    public static List<String> getAllFile(String directoryPath, boolean isAddDirectory) {
        System.out.println(directoryPath);
        List<String> list = new ArrayList<String>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if(isAddDirectory){
                    list.add(file.getAbsolutePath());
                }
                list.addAll(getAllFile(file.getAbsolutePath(),isAddDirectory));
            } else {
                list.add(file.getAbsolutePath());
            }
        }
        return list;
    }

    public static void main(String[] args) {
        String fileName = "100000.json";
        String[] arr = fileName.split(".");
        System.out.println(arr.length);
        System.out.println(fileName.lastIndexOf("."));
    }
}
